
package com.gitee.jmash.rbac.dao;

import com.gitee.jmash.common.utils.UUIDUtil;
import com.gitee.jmash.core.orm.jpa.BaseDao;
import com.gitee.jmash.core.orm.jpa.TenantEntityManager;
import com.gitee.jmash.rbac.entity.RolesDutyEntity;
import com.gitee.jmash.rbac.entity.RolesDutyEntity.DutyPk;
import java.util.List;
import java.util.UUID;
import jmash.rbac.protobuf.DutyType;
import jmash.rbac.protobuf.RoleDuty;
import org.apache.commons.lang3.StringUtils;

/**
 * Duty实体的Dao层（使用JPA实现）.
 *
 * @author <a href="mailto:service@crenjoy.com">crenjoy</a>
 */
public class RolesDutyDao extends BaseDao<RolesDutyEntity, DutyPk> {

  public RolesDutyDao() {
    super();
  }

  public RolesDutyDao(TenantEntityManager tem) {
    super(tem);
  }

  /** 职责分离类型查询. */
  public List<RolesDutyEntity> findDutyList(DutyType dutyType) {
    String sql = "select s from RolesDutyEntity s where s.dutyType = ?1 ";
    return this.findList(sql, dutyType);
  }

  /** 获取角色职责对应列表. */
  public List<RolesDutyEntity> findDutyList(UUID roleId) {
    String sql = "select s from RolesDutyEntity s where s.srcRoleId = ?1 ";
    return this.findList(sql, roleId);
  }

  /** 移除职责分离. */
  public int removeByRoleId(UUID roleId) {
    String sql = "delete from RolesDutyEntity s where s.srcRoleId = ?1 ";
    return this.executeUpdate(sql, roleId);
  }

  /** 编辑角色职责. */
  public void updateRoleDuty(UUID roleId, List<RoleDuty> roleDutyList) {
    this.removeByRoleId(roleId);
    if (roleDutyList != null && roleDutyList.size() > 0) {
      for (RoleDuty roleDuty : roleDutyList) {
        if (StringUtils.isBlank(roleDuty.getRoleId()))
          continue;
        RolesDutyEntity entity = new RolesDutyEntity(roleId,
            UUIDUtil.fromString(roleDuty.getRoleId()), roleDuty.getDutyType());
        this.persist(entity);
      }
    }
  }

  /** 是否关联角色. */
  public boolean isRelationRole(UUID roleId) {
    String sql = "select count(s.srcRoleId) from RolesDutyEntity s where s.descRoleId = ?1 ";
    Object count = this.findSingleResult(sql, roleId);
    return Integer.parseInt(count.toString()) > 0 ? true : false;
  }

}
